/*
 * @Description: 标签解析 Extension
 * @Author: DHL
 * @Date: 2022-04-20 14:21:27
 * @LastEditors: DHL
 * @LastEditTime: 2022-10-13 11:10:10
 */
import { some } from 'lodash-es'

const ALLOWED_TYPES: any = {
  FailedJobRetryTimeCycle: [
    'bpmn:StartEvent',
    'bpmn:BoundaryEvent',
    'bpmn:IntermediateCatchEvent',
    'bpmn:Activity'
  ],
  Connector: ['bpmn:EndEvent', 'bpmn:IntermediateThrowEvent'],
  Field: ['bpmn:EndEvent', 'bpmn:IntermediateThrowEvent']
}

function is(element: { $instanceOf: (arg0: any) => any }, type: string) {
  return element && typeof element.$instanceOf === 'function' && element.$instanceOf(type)
}

function exists(element: string | any[]) {
  return element && element.length
}

function includesType(collection: any, type: string) {
  return (
    exists(collection) &&
    some(collection, function (element: { $instanceOf: (arg0: any) => any }) {
      return is(element, type)
    })
  )
}

function anyType(element: { $instanceOf: (arg0: any) => any }, types: any) {
  return some(types, function (type: string) {
    return is(element, type)
  })
}

function isAllowed(propName: string, propDescriptor: { name: any }, newElement: any) {
  var name = propDescriptor.name,
    types = ALLOWED_TYPES[name.replace(/flowable:/, '')]

  return name === propName && anyType(newElement, types)
}

function FlowableModdleExtension(eventBus: any) {
  eventBus.on(
    'property.clone',
    function (context: any) {
      var newElement = context.newElement,
        propDescriptor = context.propertyDescriptor

      FlowableModdleExtension.prototype.canCloneProperty(newElement, propDescriptor)
    },
    FlowableModdleExtension
  )
}

FlowableModdleExtension.$inject = ['eventBus']

FlowableModdleExtension.prototype.canCloneProperty = function (
  newElement: { eventDefinitions: any; loopCharacteristics: { $instanceOf: (arg0: any) => any } },
  propDescriptor: any
) {
  if (isAllowed('flowable:FailedJobRetryTimeCycle', propDescriptor, newElement)) {
    return (
      includesType(newElement.eventDefinitions, 'bpmn:TimerEventDefinition') ||
      includesType(newElement.eventDefinitions, 'bpmn:SignalEventDefinition') ||
      is(newElement.loopCharacteristics, 'bpmn:MultiInstanceLoopCharacteristics')
    )
  }

  if (isAllowed('flowable:Connector', propDescriptor, newElement)) {
    return includesType(newElement.eventDefinitions, 'bpmn:MessageEventDefinition')
  }

  if (isAllowed('flowable:Field', propDescriptor, newElement)) {
    return includesType(newElement.eventDefinitions, 'bpmn:MessageEventDefinition')
  }
}

export default FlowableModdleExtension
